package com.zwjstudy.cachestudy.redis7.lettuce.distributed.config;

import io.lettuce.core.ReadFrom;
import org.springframework.boot.autoconfigure.data.redis.LettuceClientConfigurationBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * ClassName: RedisConfig
 * Package: com.zwjstudy.cachestudy.redis7.lettuce.masterslave.config
 * Description:
 *
 * @Author: 张文俊
 * @Create: 2025-09-12 - 11:30
 * @Version: v1.0
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate redisTemplate(LettuceConnectionFactory lettuceConnectionFactory) {
        RedisTemplate template = new RedisTemplate<>();
        template.setConnectionFactory(lettuceConnectionFactory);
        // 使用 String 序列化 key
        template.setKeySerializer(new StringRedisSerializer());
        // 使用 JSON 序列化 value，推荐 Jackson
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        // 对于 Hash 结构，同样设置 key 和 value 的序列化器
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    /*
    *   读写分离配置
    *   Lettuce 支持配置读取策略，例如优先从副本节点读取以减轻主节点压力
    *   可选策略包括 MASTER（仅主）、MASTER_PREFERRED（优先主）、REPLICA（仅从）、REPLICA_PREFERRED（优先从）。
    *
    * */
    @Bean
    public LettuceClientConfigurationBuilderCustomizer lettuceCustomizer() {
        return builder -> builder.readFrom(ReadFrom.REPLICA_PREFERRED);
    }
}
